/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.cleaner;

import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.kramerius.fedoraaccess.FedoraConnector;
import java.util.List;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class PeriodicalRemover extends AbstractRemover {

    private final XPath volumePidsXpath = Dom4jUtils.createXPath("/rdf:RDF/rdf:Description/kramerius:hasVolume/@rdf:resource");
    private final XPath itemPidsXpath = Dom4jUtils.createXPath("/rdf:RDF/rdf:Description/kramerius:hasItem/@rdf:resource");

    public PeriodicalRemover(FedoraConnector con) {
        super(con);
    }

    public void removePeriodical(String periodicalPid) {
        System.out.println("periodical pid: '" + periodicalPid + "'");
        removePeriodicalVolumes(periodicalPid);
        purgeDigitalObject(periodicalPid);
        System.out.println("periodical removed");
    }

    private void removePeriodicalVolumes(String periodicalPid) {
        List<String> volumePidList = findPidsOfPeriodicalVolumes(periodicalPid);
        System.out.println("volumes: " + volumePidList.size());
        for (String volumePid : volumePidList) {
            removePeriodicalVolume(volumePid);
        }
    }

    private List<String> findPidsOfPeriodicalVolumes(String periodicalPid) {
        return findPidsOfReferencedEntities(periodicalPid, volumePidsXpath);
    }

    private void removePeriodicalVolume(String volumePid) {
        System.out.println("volume pid: '" + volumePid + "'");
        removeInternalParts(volumePid);
        removePeriodicalItems(volumePid);
        removePages(volumePid);
        purgeDigitalObject(volumePid);
        System.out.println("volume removed");
    }

    private void removePeriodicalItems(String parentObjectPid) {
        List<String> itemPidList = findPidsOfPeriodicalItems(parentObjectPid);
        System.out.println("items: " + itemPidList.size());
        for (String itemPid : itemPidList) {
            removePeriodicalItem(itemPid);
        }
    }

    private List<String> findPidsOfPeriodicalItems(String periodicalVolumePid) {
        return findPidsOfReferencedEntities(periodicalVolumePid, itemPidsXpath);
    }

    private void removePeriodicalItem(String itemPid) {
        System.out.println("item pid: '" + itemPid + "'");
        removeInternalParts(itemPid);
        removePages(itemPid);
        purgeDigitalObject(itemPid);
        System.out.println("item removed");
    }
}
